import moment from 'moment'

export function proxyToData(proxyObject){
    if(! proxyObject instanceof Proxy){
        return proxyObject
    }
    if(typeof proxyObject !=="object"){
        return proxyObject
    }
    if(proxyObject === null){
        return ""
    }
    if(proxyObject instanceof Date){
        return moment(proxyObject).format('yyyy-MM-DD HH:mm:ss')
    }
    let data
    if(!proxyObject.length){
        data = {};
        for (let key in proxyObject){
            data[key] = proxyToData(proxyObject[key])
        }
    }else{
        data = [];
        for (let key in proxyObject){
            data.push(proxyObject[key])
        }
    }
    return data
}

export function checkCookieField(cookie_obj){
    return 'PHPSESSID' in cookie_obj
}

export function checkCookieIsExpire(cookie_obj) {
    if(!checkCookieField(cookie_obj)){
        return false
    }
    const dateObj = new Date(cookie_obj.PHPSESSID.expires);
    const curDateObj = new Date()
    return ( dateObj.getTime()- curDateObj.getTime() ) < 0

}

export function checkCookieIsSoonVoid(cookie_obj){
    if(!checkCookieField(cookie_obj)){
        return false
    }
    const dateObj = new Date(cookie_obj.PHPSESSID.expires);
    const curDateObj = new Date()
    return (dateObj.getTime() - curDateObj.getTime()) < 7 * 24 * 3600;
}

export function getFormatSessionExpire(cookie_obj){
    return formatDate(cookie_obj.PHPSESSID.expires)
}

export function formatDate(date = null){

    const dateObj = date ? new Date(date) : new Date();
    return moment(dateObj).format('yyyy-MM-DD HH:mm:ss')
}

function parseCookies(cookieString) {
    const cookies = {};

    // 分割Cookie字符串
    const cookieArray = cookieString.split(/,\s+(?=[^;,]*=)/);

    // 遍历每个Cookie
    for (const cookie of cookieArray) {
        let cookiesObj = {};
        // 分割每个Cookie的键值对
        const keyValueArray = cookie.split('; ');

        // 取第一个键值对作为Cookie的主体
        const [cookieValue, ...attributes] = keyValueArray;

        // 分割键值对
        const [key, value] = cookieValue.split('=');

        // 添加到对象中
        cookies[key] = cookiesObj;
        cookiesObj.value =value
        // 处理Cookie的属性
        for (const attribute of attributes) {
            const [attrKey, attrValue] = attribute.split('=');
            // 去除前导空格
            const trimmedAttrKey = attrKey.trim();
             // 如果没有值，则默认为true
            // 添加属性到对象中
            cookiesObj[trimmedAttrKey] = attrValue ? attrValue.trim() : true;
        }
    }

    return cookies;
}